'''
Created on Mar 8, 2016

@author: JimmyMo
'''
import re
import itertools
# def to_flat_list(nested_list):
#     li=[[1,2],[3,4],[5,6]]
#     test_astar(*"abc")
#     print(list(chain(*li)))
#     pass
def generate_patterns(template_path, in_proc=True, output_path='pattern.output'):
    r_lines = []
    with open(template_path, "r") as f1:
        lines = f1.readlines()
#         lines_decode = [elem.decode('utf-8') for elem in lines]
        a_lines = [elem for elem in lines if not elem.startswith("###")]
        r_lines = list(map(__expand, a_lines))
    
    if not in_proc:
        print("writting to %s..." % output_path)
        with open(output_path, "w+") as f2:
            for l in r_lines:
                f2.writelines([elem + '\n' for elem in l])
        print("done writting...")
    else:
        return list(itertools.chain(*r_lines))
    pass
# def ___filter_comments(pattern_line):
#     pattern_line.startswith("###")
def __expand(pattern_line):
    li = []
    if pattern_line.find('`') < 0:
        return []
#         return [pattern_line]
    
    (min, max) = __parse_num(pattern_line)
    for i in range(min, max):
#         txt = re.sub(r'`.*?`', str(i).zfill(4), pattern_line, count=1, flags=re.IGNORECASE)
        txt = re.sub(r'`.*?`', str(i), pattern_line, count=1)
        if txt.find('`') < 0:
            li.append(txt)
        li = li + __expand(txt)
        
    return li

def __parse_num(pattern_line):
    p = re.compile("`(.*?)`")
    ranges = p.findall(pattern_line)
    one_range = ranges[0]
    tmp = one_range.split('-')
    return (int(tmp[0]), int(tmp[1]))
    pass

if __name__ == "__main__":
    generate_patterns("log_json_patterns.conf.template", in_proc=False, output_path="json_json_patterns.conf.output", )
#     to_flat_list(None)